import { getInstallConfigApi, installSaveApi } from '@/api/system/user/user'
import { InstallParam } from '@/api/system/user/UserModel'
import { Result, StatusCode } from '@/http/request'
import { onMounted, ref } from 'vue'
import { ElForm } from 'element-plus'
import useInstance from '@/hooks/useInstance'
import { useRouter } from 'vue-router'

export default function useInstall(installModel: InstallParam) {
    const { global } = useInstance()
    const router = useRouter()

    const isCanSubmit = ref(true)
    const submitText = ref('提交')

    // 表单ref属性
    const installForm = ref<InstanceType<typeof ElForm>>()

    const getInstallConfig = async () => {
        let res = await getInstallConfigApi()
        if (res && res.code == StatusCode.Success) {
            installModel.baseURL = res.data.system.baseURL
            installModel.serverPort = res.data.system.serverPort
            installModel.mysqlAddr = res.data.mysql.addr
            installModel.mysqlDBName = res.data.mysql.dbname
            installModel.mysqlUsername = res.data.mysql.username
            installModel.mysqlPassword = res.data.mysql.password
            installModel.redisAddr = res.data.redis.addr
            installModel.redisPassword = res.data.redis.password
        }
    }

    const installSave = () => {
        installForm.value?.validate(async (valid) => {
            if (valid) {
                isCanSubmit.value = false
                submitText.value = '提交中，请等待...'
                let res: Result
                res = await installSaveApi(installModel)
                if (res && res.code == StatusCode.Success) {
                    isCanSubmit.value = true
                    submitText.value = '提交'
                    router.push({ path: '/login' })
                    // 信息提示
                    global.$message({ message: res.msg, type: 'success' })
                }
            }
        })
    }

    onMounted(() => {
        getInstallConfig()
    })

    return {
        isCanSubmit,
        submitText,
        installForm,
        installSave
    }
}
